import React, { useRef, useState } from 'react';
import { Row, Col, Badge, Tag, Descriptions } from 'antd';
import  {DrawerForm,ProFormInstance,} from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import * as c from '@/services/consts';
import {  CheckCircleFilled, ClockCircleFilled, CloseCircleFilled,} from '@ant-design/icons';
import * as api from '@/services/vpnServerDeploy';
import { ProTable } from '@ant-design/pro-components';
import dayjs from 'dayjs';

type VpnServerFormProps = {
  visible: boolean;
  current: API.VpnServerDeploy | undefined;
  onCancel: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, current, onCancel } = props;

  if (!visible) {
    return null;
  }
  const formRef = useRef<ProFormInstance>();
  // const editorFormRef = useRef<EditableFormInstance<API.VpnServerDeployServer>>();
  // const editorActionRef = useRef<ActionType>();

  const [dataSource, setDataSource] = useState<API.VpnServerDeploy|undefined>(undefined);
  // const [serverSource, setServerSource] = useState<API.VpnServerDeployServer[]|undefined>(undefined);
  const [configSource, setConfigSource] = useState<API.VpnServerDeployConfig|undefined>(undefined);
  // const [myloading, setMyloading] = useState<boolean>(true);
  

  const loadData = async () => {
    if(current){
      const result = await api.get({id:current.id});
      if (result && result.success) {
        setDataSource(result.data);
        // setServerSource(result.data.servers);
        setConfigSource(result.data.config)
        formRef.current?.setFieldValue('type', result.data.config.type);
      }
      return Promise.resolve(result.data);
    }
    else{
      let empty : API.VpnServerDeploy = {id:'', status:0, udp:true, config:undefined, servers:[]};
      return Promise.resolve(empty);
    }
  };
  

  // const loadData = async () => {
  //   const result = await api.get({ id:current.id });
  //   if (result && result.success) {
  //     setDataSource(result.data);
  //   }
  //   setMyloading(false);
  // };

  // useEffect(() => {
  //   loadData();
  // }, []);


  

  const columns: ProColumns<API.VpnServerDeployServer>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'success',
      renderText: (val) => {
        return val == true ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : val == false ? (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        ) : (
          <Badge count={<ClockCircleFilled style={{ color: '#999' }} />} />
        );
      },
    },
    {
      title: '实例ID',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: '服务器IP',
      dataIndex: 'ip',
      width: 130,
    },
    {
      title: '完成时间',
      dataIndex: 'completeTime',
      width: 160,
    },
    {
      title: '信息',
      dataIndex: 'message',
      ellipsis: true,
      // render: (_, record) => {
      //   return record.server?.remark;
      // },
    },
  ];


  return (
    <DrawerForm<API.VpnServerDeploy>
      visible={visible}
      // initialValues={dataSource}
      title={<>服务器部署结果 {dataSource?.status == 2 ? <Tag color='#52c41a'>完成</Tag>
      : dataSource?.status == 3 ? <Tag color='error'>关闭</Tag>
      : dataSource?.status == 1 ? <Tag color='blue'>安装中</Tag> 
      : <Tag color='orange'>待运行</Tag>}
      </>}
      formRef={formRef}
      autoFocusFirstInput
      width={1000}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        // maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
      request={loadData}
    >
      <Row gutter={24}>
        <Col span={24}>
        <Descriptions title="" bordered column={2} labelStyle={{width:120, fontWeight:'bold'}}>
          <Descriptions.Item label="部署类型">{c.getObjectText(c.ServerDeployTypes, configSource?.type)}</Descriptions.Item>
          <Descriptions.Item label="UDP">{dataSource?.udp == true ? <Tag color='success'>启用</Tag> : <Tag color='error'>禁用</Tag>}</Descriptions.Item>
          <Descriptions.Item label="备注信息" span={2}>{dataSource?.remark}</Descriptions.Item>
        </Descriptions>
        </Col>

        <Col span={24}>
      
      {configSource?.actions?.map((act) => {
        return (
          <ProTable<API.VpnServerDeployServer>
            rowKey="id"
            style={{marginTop:20, marginLeft:-25}}
            // actionRef={actionRef}
            headerTitle={
              <b>{c.getObjectText(c.ServerDeployTypes, act.action)}&nbsp;
              <Tag color='blue'>{act.beginTime ? <>开始：{dayjs(act.beginTime).format('YYYY-MM-DD HH:mm:ss')} {act.endTime ? ` 结束：${dayjs(act.endTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</> : '未开始'}</Tag>
                {/* {dataSource?.createTime ? (
                  moment(new Date()).format('yyyy-MM-dd') !=
                  moment(dataSource?.createTime).format('yyyy-MM-dd') ? (
                    <Tag color="error">非当天检测结果</Tag>
                  ) : (
                    ''
                  )
                ) : (
                  ''
                )}
                　
                {dataSource?.checkConfig?.uncheckBlock == true ? (
                  <Tag color="blue">不检测被墙</Tag>
                ) : (
                  ''
                )} */}
              </b>
            }
            options={{
              fullScreen: false,
              reload: false,
              setting: false,
              density: false,
            }}
            search={false}
            pagination={false}
            columns={columns}
            expandable={undefined}
            dataSource={act.servers}
            // toolbar={{
            //   filter: (
            //     <>
            //     </>
            //   ),
            // }}
            // rowSelection={{
            //   defaultSelectedRowKeys: [],
            //   onChange: (selectedRowKeys, selectedRows) => {
            //     setSelectIds(selectedRowKeys);
            //   },
            // }}
            // tableAlertRender={({
            //   selectedRowKeys,
            //   selectedRows,
            //   onCleanSelected,
            // }) => (
            // )}
          />

        );
      })}
        </Col>
      </Row>

    </DrawerForm>
  );
};

export default VpnServerForm;
